//
//  LGSportRecordChartView.m
//  XieHeHeartDisease
//
//  Created by 1234 on 2024/2/28.
//

#import "LGSportRecordChartView.h"
#import "LGScrollView.h"

#define topMargin     viewPix(7)

#define leftMargin    (viewPix(35)+iPadMargin(10))

//#define lineHeight    viewPix(35)

#define scrollWidth   (Screen_W - viewPix(32))

#define scrollHeight   viewPix(210)

@interface LGSportRecordChartView()<UIScrollViewDelegate>
/**   */
@property (nonatomic , strong)UIButton *leftBtn;
/**   */
@property (nonatomic , strong)UILabel *monthLabel;
/**   */
@property (nonatomic , strong)UIButton *rightBtn;
/**   */
@property (nonatomic , strong)UIView *baseView;
/**   */
@property (nonatomic , strong)LGScrollView *scrollView;
/**   */
@property (nonatomic , strong)UILabel *unitLabel;
/**   */
@property (nonatomic , strong)UILabel *valueLabel;
/**   */
@property (nonatomic , assign)NSInteger totalCount;
/**   */
@property (nonatomic , assign)CGFloat itemWidth;
/**   */
@property (nonatomic , assign)CGFloat lineHeight;
/**   */
@property (nonatomic , strong)NSMutableArray *buttonArray;
/**   */
@property (nonatomic , strong)NSArray *yAxis;
/**   */
@property (nonatomic , strong)NSArray *xAxis;
/**   */
@property (nonatomic , strong)NSArray *dataArray;
/**   */
@property (nonatomic , strong)NSDateFormatter *formatter;
/**   */
@property (nonatomic , assign)CGFloat margin;

@end

@implementation LGSportRecordChartView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.margin = 20;
        self.yAxis = @[@"0",@"20",@"40",@"60"];
        self.itemWidth = scrollWidth/7.0;
        [self createSubView];
    }
    return self;
}

-(void)setDataDic:(NSDictionary *)dataDic{
    _dataDic = dataDic;
    for (UIView *subView in self.scrollView.subviews) {
        [subView removeFromSuperview];
    }
    if([dataDic isKindOfClass:[NSDictionary class]] && dataDic.allKeys.count>0){
        self.xAxis = dataDic[@"xAxis"];
        self.dataArray = dataDic[@"series"];
    }
}

-(void)setYAxis:(NSArray *)yAxis{
    _yAxis = yAxis;
    self.lineHeight = floor((scrollHeight-viewPix(20))/yAxis.count);
    for (NSInteger i=0; i<yAxis.count; i++) {
        //Y轴标题
        UILabel *label = [UILabel lableWithText:LGNSString(yAxis[yAxis.count-1-i]) colorString:@"#5C5C5C" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        label.frame = CGRectMake(0, topMargin+self.lineHeight*i, leftMargin, self.lineHeight);
        label.tag = 4000+i;
        [self.baseView addSubview:label];
    }
}

//创建X轴坐标
-(void)setXAxis:(NSArray *)xAxis{
    _xAxis = xAxis;
    self.totalCount = xAxis.count>0?xAxis.count:1;
    NSInteger count = (self.totalCount>7)?7:self.totalCount;
    self.itemWidth = scrollWidth/count;
    CGFloat totalWidth = viewPix(20)+self.itemWidth*self.totalCount;
    self.scrollView.contentSize = CGSizeMake(totalWidth, scrollHeight);
    [self.scrollView setContentOffset:CGPointMake(totalWidth-scrollWidth-viewPix(10), 0)];
    //虚线
    for (NSInteger i=0; i<self.yAxis.count; i++) {
        LGDottedLineView *lineView = [[LGDottedLineView alloc]initWithFrame:CGRectMake(0, self.lineHeight*i, self.itemWidth*xAxis.count+viewPix(50), self.lineHeight)];
        [self.scrollView addSubview:lineView];
    }
    
    //日期
    for (NSInteger i=0; i<xAxis.count; i++) {
//        NSArray *tempArray = [LGNSString(xAxis[i]) componentsSeparatedByString:@"-"];
//        NSString *dayString = [NSString stringWithFormat:@"%@/%@",tempArray[tempArray.count-2],tempArray[tempArray.count-1]];
        UILabel *dayLabel = [UILabel lableWithText:LGNSString(xAxis[i]) colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        dayLabel.frame = CGRectMake(viewPix(10)+self.itemWidth*i, scrollHeight-viewPix(30), self.itemWidth, viewPix(20));
        dayLabel.tag = 1000+i;
        [self.scrollView addSubview:dayLabel];
        if([LGNSString(xAxis[i]) isEqualToString:@"今日"]){
            CGFloat offset = self.itemWidth*i-(Screen_W-viewPix(32)-leftMargin)/2.0;
            offset = (offset>0)?offset:0;
            [self.scrollView setContentOffset:CGPointMake(offset, 0)];
        }
    }
}
-(void)setDataArray:(NSArray *)dataArray{
    _dataArray = dataArray;
    CGFloat maxValue = 0;
    for (NSInteger i=0; i<dataArray.count; i++) {
        maxValue = [dataArray[i] floatValue]>maxValue?[dataArray[i] floatValue]:maxValue;
    }
    maxValue = maxValue<3?3:maxValue;
    self.margin = maxValue/3.0;
    for (NSInteger i=0; i<self.yAxis.count; i++) {
        UILabel *label = [self viewWithTag:4003-i];
        label.text = [NSString stringWithFormat:@"%.1f",self.margin*i];
    }
    self.buttonArray = [NSMutableArray array];
    NSMutableArray *pointArray = [NSMutableArray array];
    CGFloat minValue = [self.yAxis[0] floatValue];
//    CGFloat marginV = [self.yAxis[1] floatValue] - [self.yAxis[0] floatValue];
    for (NSInteger i=0; i<dataArray.count; i++) {
        CGFloat buttonH = floor(([dataArray[i] floatValue]-minValue)/self.margin*self.lineHeight);
        CGFloat marginY = scrollHeight-viewPix(20)-self.lineHeight/2.0-buttonH-1;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(self.itemWidth/2.0+self.itemWidth*i, marginY, viewPix(12), buttonH);
        [button setBackgroundColor:[UIColor colorWithString:@"#A8CFFD"] forState:UIControlStateNormal];
        [button setBackgroundColor:[UIColor colorWithString:kThemeColor] forState:UIControlStateSelected];
        button.tag = 2000+i;
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:button.bounds byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:CGSizeMake(viewPix(6), viewPix(6))];
        CAShapeLayer *layer = [[CAShapeLayer alloc] init];
        layer.frame = button.bounds;
        layer.path = path.CGPath;
        button.layer.mask = layer;
        [self.scrollView addSubview:button];
        [self.buttonArray addObject:button];
        
        UIButton *actionButton = [UIButton buttonWithType:UIButtonTypeCustom];
        actionButton.frame = CGRectMake(self.itemWidth*i, 0, self.itemWidth, scrollHeight);
        actionButton.tag = 3000+i;
        [actionButton addTarget:self action:@selector(pointButtonTouch:) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:actionButton];
        
        NSValue *point = [NSValue valueWithCGPoint:button.center];
        [pointArray addObject:point];
    }
}


-(void)pointButtonTouch:(UIButton *)sender{
    NSInteger index = sender.tag-3000;
    for (UIButton *button in self.buttonArray) {
        button.selected = (button.tag-2000 == index)?YES:NO;
    }
    UIButton *button = [self viewWithTag:2000+index];
    [self.scrollView addSubview:self.valueLabel];
    [self.scrollView bringSubviewToFront:self.valueLabel];
    self.valueLabel.center = CGPointMake(button.center.x, button.frame.origin.y-viewPix(15));
    self.valueLabel.text = [NSString stringWithFormat:@"%@分钟",self.dataArray[index]];
//    NSInteger index = sender.tag%1000;
//    NSMutableArray *alertArray = [NSMutableArray array];
//    for (NSInteger i=0; i<self.dataArray.count; i++) {
//        NSDictionary *tempDic = self.dataArray[i];
//        NSArray *tempArray = tempDic[@"point"];
//        for(NSInteger j=0; j<tempArray.count; j++){
//            UIButton *button = [self viewWithTag:j];
//            button.selected = (button.tag%1000 == index)?YES:NO;
//            if(button.tag%1000 == index){
//                NSDictionary *alertDic = @{@"title":LGNSString(tempDic[@"title"]),@"score":LGNSString(tempArray[index][@"value"]),@"status":LGNSString(tempArray[index][@"status"])};
//                [alertArray addObject:tempDic];
//            }
//        }
//    }
//    CGPoint point = [self.scrollView convertPoint:sender.center toView:self.superview];
//    if(self.delegate && [self.delegate respondsToSelector:@selector(showAlertView:date:point:)]){
//        [self.delegate showAlertView:alertArray date:self.dataArray[index] point:point];
//    }
}


//-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
//    if(self.delegate && [self.delegate respondsToSelector:@selector(chartViewTouchesBegan)]){
//        [self.delegate chartViewTouchesBegan];
//    }
//}
//
//-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//    if(self.delegate && [self.delegate respondsToSelector:@selector(chartViewTouchesBegan)]){
//        [self.delegate chartViewTouchesBegan];
//    }
//}

//查看运动记录
-(void)tipButtonAction{
    
}

-(void)monthButtonTouched:(UIButton *)sender{
    NSInteger month = sender == (self.leftBtn)?-1:1;
    NSDate *date = [self.formatter dateFromString:self.monthLabel.text];
    NSDateComponents *component = [[NSDateComponents alloc]init];
    [component setMonth:month];
    NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *toDate = [calendar dateByAddingComponents:component toDate:date options:0];
    self.monthLabel.text = [self.formatter stringFromDate:toDate];
    if(self.delegate && [self.delegate respondsToSelector:@selector(selectMonth:)]){
        [self.delegate selectMonth:self.monthLabel.text];
    }
}

#pragma mark
#pragma mark ====> 创建控件
-(void)createSubView{
    [self addSubview:self.leftBtn];
    [self addSubview:self.monthLabel];
    [self addSubview:self.rightBtn];
    [self addSubview:self.baseView];
    [self.baseView addSubview:self.scrollView];
    [self.baseView addSubview:self.unitLabel];
    [self.scrollView addSubview:self.valueLabel];
    self.monthLabel.text = [self.formatter stringFromDate:[NSDate date]];
}

-(NSDateFormatter *)formatter{
    if(!_formatter){
        _formatter = [[NSDateFormatter alloc] init];
        _formatter.dateFormat = @"yyyy年MM月";
    }
    return _formatter;
}

-(UIButton *)leftBtn{
    if(!_leftBtn){
        _leftBtn = [UIButton buttonWithImage:@"日历-上个月" frame:CGRectMake(Screen_W/2.0-viewPix(110), viewPix(3), viewPix(40), viewPix(40))];
        [_leftBtn addTarget:self action:@selector(monthButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _leftBtn;
}

-(UILabel *)monthLabel{
    if(!_monthLabel){
        _monthLabel = [UILabel lableWithText:@"" colorString:@"#282828" textFont:LGFont(16) textAlignment:NSTextAlignmentCenter lines:1];
        _monthLabel.frame = CGRectMake(Screen_W/2.0-viewPix(70), viewPix(3), viewPix(140), viewPix(40));
    }
    return _monthLabel;
}

-(UIButton *)rightBtn{
    if(!_rightBtn){
        _rightBtn = [UIButton buttonWithImage:@"日历-下个月" frame:CGRectMake(Screen_W/2.0+viewPix(70), viewPix(3), viewPix(40), viewPix(40))];
        [_rightBtn addTarget:self action:@selector(monthButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightBtn;
}

-(UIView *)baseView{
    if(!_baseView){
        _baseView = [UIView shadowViewWithColor:@"#B0B2B2" offset:CGSizeMake(0, 2) opacity:0.15 radius:15];
        _baseView.frame = CGRectMake(viewPix(16), viewPix(45), Screen_W-viewPix(32), viewPix(217));
        _baseView.backgroundColor = [UIColor whiteColor];
    }
    return _baseView;
}

-(UILabel *)unitLabel{
    if(!_unitLabel){
        _unitLabel = [UILabel lableWithText:@"分钟" colorString:@"#666666" textFont:LGFont(12) textAlignment:NSTextAlignmentLeft lines:1];
        _unitLabel.frame = CGRectMake(viewPix(12), viewPix(8), 100, viewPix(17));
    }
    return _unitLabel;
}

-(LGScrollView *)scrollView{
    if(!_scrollView){
        _scrollView = [[LGScrollView alloc] initWithFrame:CGRectMake(leftMargin, topMargin, scrollWidth-leftMargin, scrollHeight)];
        _scrollView.contentSize = CGSizeMake(self.itemWidth*30+viewPix(20), scrollHeight);
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.delegate = self;
    }
    return _scrollView;
}

-(UILabel *)valueLabel{
    if(!_valueLabel){
        _valueLabel = [UILabel lableWithText:@"" colorString:@"#282828" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        _valueLabel.bounds = CGRectMake(0, 0, viewPix(80), viewPix(20));
    }
    return _valueLabel;
}



@end
